/* 
* 科技有限公司版权所有（）.
* Copyright (c) 2019,  and/or its affiliates. All rights reserved.
* @Date: 2020.09.01 22:47.
* @Author 
* @Description  项目 - 活动 新增 与 编辑
**/
<template>
  <div class="pr-add">

    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="134px" class="demo-ruleForm" :inline="true">
      <h1 class="pr-title"> 活动消息 </h1>
      <el-form-item label="活动名称：" prop="activityName">
        <el-input placeholder="请输入活动名称" v-model="ruleForm.activityName"></el-input>
      </el-form-item>

      <el-form-item label="活动状态：" prop="activityStatus">
        <el-select placeholder="请选择活动状态" v-model="ruleForm.activityStatus">
          <el-option label="已启用" value="1"></el-option>
          <el-option label="活动暂停" value="0"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="活动链接：" prop="activityUrl">
        <el-input placeholder="请输入活动链接" v-model="ruleForm.activityUrl"></el-input>
      </el-form-item>

      <h1 class="pr-title"> 活动商品 </h1>
      <ul class="pr-list">
        <li v-for="(item, index) in ruleForm.goodsInfoList" :key="index">
          <el-form-item label="活动商品ID：">
            <el-input placeholder="请输入加汇商品编号" v-model="item.id"></el-input>
          </el-form-item>

          <el-form-item label="折扣金额：">
            <el-input placeholder="请输入金额" v-model="item.salevalue" class="w105"></el-input> 元
            <el-button size="mini" type="primary" class="pr-add-btn" @click="handleAddClick" v-if="index == 0">添加</el-button>
            <el-button size="mini" type="primary" class="pr-add-btn" @click="handleDelClick(index)" v-if="index > 0">删除</el-button>
          </el-form-item>
        </li>
      </ul>

      <h1 class="pr-title"> 活动有效期 </h1>

      <el-form-item label="有效期：" prop="date1">
        <el-date-picker v-model="ruleForm.date1" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>

      <el-form-item label="适用日期：" prop="survivalDay">
        <el-checkbox-group v-model="ruleForm.survivalDay">
          <el-checkbox label="周一" value="1" name="type"></el-checkbox>
          <el-checkbox label="周二" value="2" name="type"></el-checkbox>
          <el-checkbox label="周三" value="3" name="type"></el-checkbox>
          <el-checkbox label="周四" value="4" name="type"></el-checkbox>
          <el-checkbox label="周五" value="5" name="type"></el-checkbox>
          <el-checkbox label="周六" value="6" name="type"></el-checkbox>
          <el-checkbox label="周末" value="7" name="type"></el-checkbox>
        </el-checkbox-group>
      </el-form-item>

      <el-form-item label="优惠时间：" prop="date2">
        <el-time-picker is-range v-model="ruleForm.date2" range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间" placeholder="选择时间范围">
        </el-time-picker>

        <el-checkbox label="全天" class="ml10" @change="handleDayChange" v-model="allDay"></el-checkbox>
      </el-form-item>

      <el-form-item label="券失效时间：" prop="survivalTime">
        购买后 <el-input placeholder="填写整数" v-model="ruleForm.survivalTime" class="w105"></el-input> 天
      </el-form-item>

      <h1 class="pr-title"> 活动范围 </h1>
      <el-form-item label="手机号码归属地：" required class="pr-w200">
        <ul class="pr-area">
          <li v-for="item in areaArr" :key="item">{{item}}</li>
        </ul>
        <el-button type="primary" @click="handleEditClick">
          添加<i class="el-icon-edit el-input__icon"></i>
        </el-button>
      </el-form-item>

      <el-form-item label="每月限购频次：" prop="mothNum">
        <el-input placeholder="填写整数" v-model="ruleForm.mothNum" class="w105"></el-input> 次
      </el-form-item>

      <el-form-item label="每日限购频次：" prop="dayNum">
        <el-input placeholder="填写整数" v-model="ruleForm.dayNum" class="w105"></el-input> 次
      </el-form-item>

      <el-form-item label="每日限购名额：" prop="limitNum">
        <el-input placeholder="填写整数" v-model="ruleForm.limitNum" class="w105"></el-input> 名
      </el-form-item>

      <el-form-item class="block">
        <el-button @click="resetForm('ruleForm')" type="info">取消</el-button>
        <el-button type="primary" @click="handleSaveClick('ruleForm')">保存并发布</el-button>
      </el-form-item>
    </el-form>
    <!-- 手机号码 归属地 弹窗 -->
    <el-dialog title="手机号归属地添加" :visible.sync="dialogVisible" width="40%">

      <el-cascader ref="cascader" :options="options" :props="props" clearable v-model="areaArrValue"></el-cascader>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleAreaClick">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import dayjs from 'dayjs'
import urls from '@/api/urls'
import { weekObj, weekObjDay } from '@/utils/const'
import { getData, postData } from '@/api/'

export default {
  name: 'addEdit',
  props: {},
  components: {},
  data() {
    return {
      allDay: '', // 全天状态
      areaArr: [],
      areaArrValue: '',
      ruleForm: {
        date1: '',
        date2: '',
        activityName: '',
        activityStatus: '',
        activityUrl: '',
        goodsInfoList: [{
          id: 0,// 商品ID
          salevalue: '', // 抵扣金额
        }],
        survivalTime: '', // 失效时间
        mothNum: '',
        dayNum: '',
        limitNum: '',
        delivery: false,
        survivalDay: [],
        provinceCityInfoList: [] // 活动范围
      },
      options: [],
      props: { multiple: true, value: 'value', label: 'cityName', children: 'chooseList' },
      dialogVisible: false, // 手机号码归属地 弹窗

      rules: {
        activityName: [{ required: true, message: '请输入活动名称', trigger: 'blur' }],
        activityStatus: [{ required: true, message: '请选择活动状态', trigger: 'change' }],
        activityUrl: [{ required: true, message: '请输入活动链接', trigger: 'blur' }],
        date1: [{ required: true, message: '请选择日期', trigger: 'change' }],
        date2: [{ required: true, message: '请选择日期', trigger: 'change' }],
        survivalDay: [{ required: true, message: '请至少选择一个活动日期', trigger: 'change' }],
        survivalTime: [{ required: true, pattern: /^[0-9]+$/, message: '请输入券失效时间,正整数', trigger: 'blur' }],
        mothNum: [{ required: true, pattern: /^[0-9]+$/, message: '请输入每月限购次数,正整数', trigger: 'blur' }],
        dayNum: [{ required: true, pattern: /^[0-9]+$/, message: '请输入每日限购频次,正整数', trigger: 'blur' }],
        limitNum: [{ required: true, pattern: /^[0-9]+$/, message: '请输入每日限购名额,正整数', trigger: 'blur' }],
      }
    }
  },
  watch: {},
  created() {
    console.log('this.$router.params.i*********d', this.$route.params.id)
    const id = this.$route.params.id
    if (id && id != 'add') { // 编辑
      this.getEditInfo(id)
    }
  },
  mounted() {
  },
  methods: {
    /**
     *@Description
     *@Param
     *@Return 添加 按钮 事件监听.
     **/
    handleAddClick() {
      const obj = {
        id: '',// 商品ID
        salevalue: '', // 抵扣金额
      }
      this.ruleForm.goodsInfoList.push(obj)
    },
    /**
     *@Description
     *@Return 删除 按钮 事件监听.
     **/
    handleDelClick(index) {
      this.ruleForm.goodsInfoList.splice(index, 1)
    },
    /**
     *@Description
     *@Return 全天事件监听.
     **/
    handleDayChange(e) {
      const y = dayjs().format('YYYY-MM-DD').split('-')
      this.ruleForm.date2 = [new Date(y[0], y[1], y[2], 0, 0, 0), new Date(y[0], y[1], y[2], 23, 59, 59)]
    },
    /**
     *@Description
     *@Return 手机号码归属地 - 编辑 按钮 事件监听.
     **/
    handleEditClick(ev) {
      this.dialogVisible = true
      console.log(ev);
      this.getArea()
    },
    /**
    *@Description
    *@Param
    *@Return 获取区域 按钮 事件监听.
    **/
    getArea() {
      getData({}, urls.activityAllArea).then(res => {
        res.result.provinceCityInfoList.forEach(val => {
          val.value = val.provinceId
          val.cityName = val.province
        })
        this.options = res.result.provinceCityInfoList
        console.log('res------------', res.result.provinceCityInfoList)
      })
    },
    /**
    *@Description
    *@Param
    *@Return 手机号码归属地 - 编辑 选择区域确定 按钮 事件监听.
    **/
    handleAreaClick() {
      console.log('选择值----', this.areaArrValue)
      const areaItems = []
      const provinceId = [] // 选中省的 id
      const provinceList = [] // 选中省的 对象
      const areaNode = this.$refs['cascader'].getCheckedNodes()

      this.areaArrValue.forEach(list => { // 选中的model
        if (!provinceId.includes(list[0])) {
          provinceId.push(list[0])
        }
      })

      provinceId.forEach(list => { // 选中的model
        this.options.forEach(val => { // 原数据
          if (list === val.provinceId) {
            val.chooseList = []
            provinceList.push(val)
          }
        })
      })

      areaNode.forEach(item => { // 获取 node
        if (item.level === 2) {
          areaItems.push(item.pathLabels[0] + item.pathLabels[1])
          console.log('provinceList------', provinceList)
          provinceList.forEach(val => { // 选中的model
            if (item.data.pid === val.provinceId) {
              const obj = { flag: item.checked, cityName: item.label, value: item.value }
              val.chooseList.push(obj)
            }
          })
        }
      })

      provinceList.forEach(val => {
        val.chooseNum = val.chooseList.length
      })

      this.areaArr = areaItems
      this.ruleForm.provinceCityInfoList = provinceList

      console.log('provinceList-------', provinceList)
      console.log('展示的值areaArr-------', this.areaArr)
      console.log('areaArrValue modle 选中的值---------------', this.areaArrValue)
      console.log('getCheckedNodes---------------', areaNode)
      this.dialogVisible = false
    },
    /**
     *@Description
     *@Param
     *@Return 保存、更新 按钮 事件监听.
     **/
    handleSaveClick(formName) {
      console.log('提交参数ruleForm----------', this.ruleForm)
      const weekArr = []
      this.ruleForm.survivalDay.forEach(val => {
        console.log('weekObj[val]----', weekObj[val], val)
        weekArr.push(weekObj[val])
      })

      this.ruleForm.survivalDay = weekArr.join(',')

      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.ruleForm.activityStarttime = dayjs(this.ruleForm.date1[0]).format('YYYY-MM-DD HH:mm:ss')
          this.ruleForm.activityEndtime = dayjs(this.ruleForm.date1[1]).format('YYYY-MM-DD HH:mm:ss')
          this.ruleForm.starttime = dayjs(this.ruleForm.date2[0]).format('YYYY-MM-DD HH:mm:ss')
          this.ruleForm.endtime = dayjs(this.ruleForm.date2[1]).format('YYYY-MM-DD HH:mm:ss')
          if (this.areaArr.length <= 0) {
            this.$message.warning('请选择手机号码归属地！')
            return false
          }
          const arr = []
          const len = this.ruleForm.goodsInfoList.length - 1

          this.ruleForm.goodsInfoList.forEach(async (val, index) => {
            const flag = /^[0-9]+([.]{1}[0-9]{1,2})?$/.test(val.salevalue)
            if (!flag) {
              this.$message.warning('折扣金额请输入数字！')
              return false
            }

            if (val.id == '' || val.salevalue == '') {
              this.$message.warning('活动商品ID和折扣金额！')
              return false
            }
            const url = `${urls.goodsUrl}/${val.id}`
            const res = await getData({}, url)
            val = { ...val, ...res.result }
            arr.push(val)
            if (len == index) {
              this.ruleForm.goodsInfoList = arr
              this.updata() // 提交数据
            }
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    /**
     *@Description
     *@Return 取消 按钮 事件监听.
     **/
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.$router.push('/activityList')
    },
    /**
     *@Description
     *@Return 新增编辑 数据提交 事件监听.
     **/
    updata() {
      console.log('this.ruleForm---', this.ruleForm)
      postData(this.ruleForm, urls.activitySaveUrl).then(res => {
        this.$message.success('数据保存成功！')
        this.$router.push('/activityList')
      })
    },
    /**
     *@Description
     *@Return 编辑 -- 进入 查询数据信息 回填.
     **/
    getEditInfo(id) {
      const url = `${urls.activityDetailUrl}/${id}`
      getData({ id }, url).then(res => {
        const result = res.result
        result.date1 = []
        result.date2 = []
        result.activityStatus = result.activityStatus.toString()
        result.date1[0] = new Date(result.activityStarttime)
        result.date1[1] = new Date(result.activityEndtime)
        result.date2[0] = new Date(result.starttime)
        result.date2[1] = new Date(result.endtime)
        const dayArr = []
        result.survivalDay.split(',').forEach(item => {
          dayArr.push(weekObjDay[item])
        })
        result.survivalDay = dayArr

        const arr = [] // 临时 承载 - 区域 - 展示 
        const arrId = [] // 临时 承载 - 区域 - 选中数据 
        result.provinceCityInfoList && result.provinceCityInfoList.forEach(val => {
          const checkboxArr = []
          let strName = val.province
          checkboxArr[0] = val.provinceId
          val.chooseList && val.chooseList.forEach(item => {
            strName += item.cityName
            checkboxArr[1] = item.value
          })
          arr.push(strName)
          arrId.push(checkboxArr)
        })
        this.areaArr = arr
        this.areaArrValue = arrId

        this.ruleForm = { ...this.ruleForm, ...result }
        console.log('编辑数据 获取的数据 ----', result, this.ruleForm)
      })
    },
  }
}

</script>
<style lang="scss" scoped="scoped">
.pr-add {
  .block {
    display: block;
    text-align: center;
  }
}
.w105 {
  width: 105px;
}
.pr-add-btn {
  margin-left: 100px;
}
.pr-area {
  overflow: hidden;
  li {
    float: left;
    padding: 0 5px;
    margin-bottom: 5px;
    line-height: 30px;
    margin-right: 5px;
    color: rgb(24, 144, 255);
    background: #e6f7ff;
  }
}
::v-deep .el-input__icon {
  line-height: 0;
}
// .pr-list {
//   li {
//     ::v-deep .el-form-item:nth-child(2) {
//       .el-form-item__content {
//         width: 285px;
//       }
//     }
//   }
// }

</style>
